package birdry.net
{
	
	/**
	*****************************************************************
	* Created Date : 2011.06.28
	* Latest Modified : 2011.06.28
	* @author Sangyoon Yang [birdry80]
	*****************************************************************
	*/
	
	import flash.display.Bitmap;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	import flash.utils.Dictionary;
	
	import com.greensock.events.LoaderEvent;
	import com.greensock.loading.core.LoaderCore;
	import com.greensock.loading.ImageLoader;
	import com.greensock.loading.LoaderMax;
	import com.greensock.loading.LoaderStatus;
	import com.greensock.loading.MP3Loader;
	import com.greensock.loading.SWFLoader;
	import com.greensock.loading.XMLLoader;
	
	public class MultiLoader 	{
		
		private static var _instance:MultiLoader;
		
		private var _queue:LoaderMax;
		private var _parameters:Object;
		private var _resourceList:Dictionary;
		
		public static function get instance(): MultiLoader	{
			if (!_instance)	_instance = new MultiLoader( new SingletonEnforcer() );
			return _instance;
		}
		
		public function getResource( url:String ): *	{
			return _resourceList[ url ];
		}
		
		public function addEventListener( type:String, listener:Function ): void	{	_queue.addEventListener(type, listener);	}
		public function removeEventListener( type:String, listener:Function ): void	{	_queue.removeEventListener(type, listener);	}
		
		public function loadXml( url:String, vars:Object = null, urlVariablesObj:Object = null ): void	{
			if (!urlVariablesObj)	{
				var urlRequest:URLRequest = new URLRequest( url );
				var urlVariables:URLVariables = new URLVariables();
				for ( var item: String in urlVariablesObj)	urlVariables[item] = urlVariablesObj[item];
				urlRequest.data = urlVariables;
			}
			addQueueAndLoad( urlRequest, returnVars( url, vars, "xml" ) );
		}
		public function loadSwf( url:String, vars:Object = null ): void	{	addQueueAndLoad( new URLRequest( url ), returnVars( url, vars, "swf" ) );	}
		public function loadImage( url:String, vars:Object = null ): void	{	addQueueAndLoad( new URLRequest( url ), returnVars( url, vars, "image" ) );	}
		public function loadMp3( url:String, vars:Object = null ): void	{	addQueueAndLoad( new URLRequest( url ), returnVars( url, vars, "mp3" ) );	}
		public function loadPause(): void	{	_queue.pause();	}
		public function loadResume(): void	{	_queue.resume();	}
		
		
		public function MultiLoader( singletonEnforcer:SingletonEnforcer ): void	{
			_resourceList = new Dictionary();
			_queue = new LoaderMax( { name:'mainQueue', onComplete:onQueueComplete, onChildComplete:onChildComplete } );
		}
		
		private function returnVars( url:String, vars:Object, fileType:String ): Object	{
			if (!vars)	vars = {};
			vars.url = url;
			vars.fileType = fileType;
			return vars;
		}
		
		private function addQueueAndLoad( urlRequest:URLRequest, vars:Object ):	void 		{
			var resource:Object = _resourceList[ urlRequest.url ];
			if ( resource )	{
				if ( vars.onLoadComplete != undefined ) {
					var target:Object = { rawContent:resource, vars:vars };
					var loaderEvent:LoaderEvent = new LoaderEvent(LoaderEvent.COMPLETE, target );
					if ( loaderEvent.target == null ) vars.onLoadComplete(loaderEvent) 
					else tracer("ERROR : already exist target object in LoaderEvent");
				}
				return;
			}
			var loaderCore:LoaderCore;
			switch(vars.fileType)	{
				case "xml":
					loaderCore = new XMLLoader( urlRequest, vars );
				break;
				case "swf":
					loaderCore = new SWFLoader( urlRequest, vars );
				break;
				case "mp3":
					loaderCore = new MP3Loader( urlRequest, vars );
				break;
				case "image":
					loaderCore = new ImageLoader( urlRequest, vars );
				break;
			}
			_queue.append(loaderCore);
			if ( _queue.status != LoaderStatus.LOADING )	_queue.load();	// load 중이면 queue만 추가한다
		}
		
		private function onQueueComplete( e:LoaderEvent ): void	{
			for ( var i:uint = 0; i < _queue.getChildren().length; ++i )	LoaderCore( _queue.getChildren()[i] ).dispose();
		}
		
		private function onChildComplete( e:LoaderEvent ): void	{
			var fileType:String = e.target.vars.fileType;
			var url:String = e.target.vars.url;
			trace("url : " + url);
			switch (fileType) {
				case "xml":
					_resourceList[url] = e.target.content as XML;
				break;
				case "swf":
					_resourceList[url] = e.target.rawContent;
				break;
				case "mp3":
					_resourceList[url] = e.target; // content is Sound, .channel is SoundChannel
				break;
				case "image":
					_resourceList[url] = e.target.rawContent as Bitmap;
				break;
			}
			// onComplete 이 onChildComplete보다 먼저 호출이 되는 문제 때문에
			// onLoadComplete을 추가하여 onChildComplete에서 _resourceList정리후에 onLoadComplete을 호출함.
			if (e.target.vars.onLoadComplete != undefined)	e.target.vars.onLoadComplete(e);
		}
	}
	
}

class SingletonEnforcer	{
}

/**
	MultiLoader.instance.load('xml/userData.xml', { onLoadComplete:onLoadComplete, onProgress:onProgress } );
	MultiLoader.instance.load('resource/2.png', { onLoadComplete:onLoadComplete, onProgress:onProgress, fileName:'2.png' } );
	MultiLoader.instance.addEventListener(LoaderEvent.COMPLETE, onQueueComplete);
	MultiLoader.instance.addEventListener(LoaderEvent.PROGRESS, onQueueProgress);

	function onProgress(e:LoaderEvent): void	{
	}
	function onLoadComplete(e:LoaderEvent): void	{
		var mc:MovieClip = e.target.rawContent as MovieClip;
		var soundChannel:SoundChannel = e.target.channel;
		var fileName:String = e.target.vars.fileName;
		trace( "onLoadComplete : " + MultiLoader.instance.getResource(e.target.name) );
	}
	function onQueueProgress(e:LoaderEvent):void 		{
		trace( "onQueueProgress : " + e.target.progress + " - " + e.target.bytesLoaded + "/" + e.target.bytesTotal );
	}
	function onQueueComplete(e:LoaderEvent):void 		{
		e.target.removeEventListener(LoaderEvent.COMPLETE, onQueueComplete);
		e.target.removeEventListener(LoaderEvent.PROGRESS, onQueueProgress);
		trace( "onQueueComplete : " + onLoadComplete );
	}
**/
	
/**
	<?xml version="1.0" encoding="iso-8859-1"?>
	<data>
		<LoaderMax name="dynamicLoaderMax" load="true" prependURLs="http://www.greensock.com/">
			<ImageLoader name="photo1" url="img/photo1.jpg" />
			<ImageLoader name="logo" url="img/corporate_logo.png" estimatedBytes="2500" />
			<SWFLoader name="mainSWF" url="swf/main.swf" autoPlay="false" estimatedBytes="15000" />
			<MP3Loader name="audio" url="mp3/intro.mp3" autoPlay="true" loops="100" />
		</LoaderMax>
	</data>
	
	
	// ImageLoader 를 활성화
	LoaderMax.activate( [ImageLoader] );
 
	var loader:XMLLoader = new XMLLoader("xml/doc.xml", {name:"xmlDoc", onComplete:completeHandler});
	loader.load();
	 
	function completeHandler(event:LoaderEvent):void {
		// xml 파일에 정의되어있던 name="photo1" 속성을 가진 ImageLoader 를 찾아서 content 를 가져옴
		var photo:ContentDisplay = LoaderMax.getContent("photo1");
		addChild(photo);
	}
**/